"""
Application-wide constants, data, and directories.
"""

import imp
import os.path
import sys

import os_helpers

class Application(object):
    title = 'MEHF'
    version = '0.1'
    url = 'http://code.google.com/p/mehf/'
    
    stackexchange_api_key = '-csIF8qleEu2U1My3jRAXQ'

    def __init__(self):
        self.user_dir = self.MakeUserDirectory()
        if self.user_dir is None:
            raise Exception("Unable to initialize user data directory!")

    def MakeUserDirectory(self):
        """
        Creates the directory for storing per-user data and returns its path name.
        """
        try_dirs = []
        if 'nt' in os_helpers.name_list:
            if os.environ.has_key('APPDATA'):
                try_dirs.append(os.path.join(os.environ['APPDATA'], self.title))
        try_dirs.append(os.path.expanduser(os.path.join("~", "." + self.title.lower())))
        try_dirs.append(os.path.join(Application.module_path(), "Data"))
        for d in try_dirs:
            try:
                os_helpers.mkdir_p(d)
                return d
            except:
                pass
            return None

    @staticmethod
    def image_path(*args):
        """
        Returns the full pathname to an image resource that's included within
        the application.
        
        *args are the image path components.
        """
        path = [":/images"]
        path.extend(args)
        return "/".join(path)

    @staticmethod
    def main_is_frozen():
        """Returns whether we are frozen via py2exe.
        This will affect how we find out where we are located.
        
        See http://www.py2exe.org/index.cgi/HowToDetermineIfRunningFromExe.
        """
        
        return (hasattr(sys, "frozen") or # new py2exe
                hasattr(sys, "importers") # old py2exe
                or imp.is_frozen("__main__")) # tools/freeze
    
    @staticmethod
    def module_path():
        """ This will get us the program's directory,
        even if we are frozen using py2exe
        
        See http://www.py2exe.org/index.cgi/WhereAmI
        """
    
        if Application.main_is_frozen():
            return os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( )))
    
        return os.path.dirname(unicode(__file__, sys.getfilesystemencoding( )))
